<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'

// ==================== 数据定义 ====================
const router = useRouter()

// 考试模式：exam（考试模式）或 practice（练习模式）
const examMode = ref('exam')
// 练习模式下的子模式：chapter（章节练习）或 random（随机练习）
const practiceMode = ref('chapter')
// 章节选择（1-8章）
const selectedChapter = ref(1)

// ==================== 常量定义 ====================
// 各种模式下的题目数量配置
const QUESTION_COUNTS = {
  exam: { single: 140, multiple: 10, trueFalse: 40 },
  random: { single: 38, multiple: 38, trueFalse: 38 },
  wrong: { single: 40, multiple: 40, trueFalse: 40 },
  chapter: { single: 50, multiple: 50, trueFalse: 50 },
  default: { single: 38, multiple: 38, trueFalse: 38 }
}

// ==================== 监听器 ====================
// 当练习模式改变时，重置章节选择
watch(practiceMode, (newVal) => {
  if (newVal === 'chapter') {
    selectedChapter.value = 1
  }
})

// ==================== 方法定义 ====================
/**
 * 生成考试
 */
const generateExam = () => {
  // 根据模式设置题目数量
  let { single, multiple, trueFalse } = getQuestionCounts()
  
  // 跳转到考试页面，传递模式参数和题目数量
  router.push({
    path: '/exam',
    query: {
      single,
      multiple,
      trueFalse,
      mode: examMode.value,
      practiceMode: practiceMode.value,
      chapter: selectedChapter.value
    }
  })
}

/**
 * 获取题目数量配置
 */
const getQuestionCounts = () => {
  if (examMode.value === 'exam') {
    return QUESTION_COUNTS.exam
  } else if (practiceMode.value === 'random') {
    return QUESTION_COUNTS.random
  } else if (practiceMode.value === 'wrong') {
    return QUESTION_COUNTS.wrong
  } else if (practiceMode.value === 'chapter') {
    return QUESTION_COUNTS.chapter
  } else {
    return QUESTION_COUNTS.default
  }
}

/**
 * 查看考试记录
 */
const viewExamRecords = () => {
  router.push('/result')
}

/**
 * 清理不再被引用的随机题库
 */
const cleanupUnusedRandomExams = (examHistory) => {
  // 获取所有在历史记录中存在的随机练习ID
  const usedRandomExamIds = new Set();
  examHistory.forEach(record => {
    if (record.examType === 'random' && record.examId) {
      usedRandomExamIds.add(record.examId);
    }
  });

  // 遍历localStorage中的所有key
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    // 检查是否为随机练习题目数据
    if (key && key.startsWith('randomExam_')) {
      // 提取examId
      const examId = key.substring(11); // 'randomExam_'.length = 11
      // 如果该examId不在使用中的ID集合中，则删除
      if (!usedRandomExamIds.has(examId)) {
        localStorage.removeItem(key);
      }
    }
  }
}

// ==================== 生命周期钩子 ====================
// 在组件挂载时执行清理操作
onMounted(() => {
  // 获取历史记录
  const historyStr = localStorage.getItem('examHistory');
  if (historyStr) {
    try {
      const examHistory = JSON.parse(historyStr);
      // 清理不再被引用的随机题库
      cleanupUnusedRandomExams(examHistory);
    } catch (e) {
      console.error('解析历史记录失败:', e);
    }
  }
})
</script>

<template>
  <div class="exam-entry">
    <h1>考试系统</h1>
    <p class="description">欢迎使用考试系统！请选择模式并开始考试。</p>
    
    <div class="mode-selection">
      <h3>选择模式</h3>
      <div class="mode-options">
        <div 
          :class="['mode-option', { active: examMode === 'exam' }]"
          @click="examMode = 'exam'"
        >
          <h4>考试模式</h4>
          <p>正式考试环境，不显示答案和解析</p>
          <p class="question-count">题目数量：单选140题，多选10题，判断40题</p>
        </div>
        
        <div 
          :class="['mode-option', { active: examMode === 'practice' }]"
          @click="examMode = 'practice'"
        >
          <h4>练习模式</h4>
          <p>学习练习环境，可查看答案和解析</p>
          <p class="question-count">题目数量：单选38题，多选38题，判断38题</p>
        </div>
      </div>
      
      <!-- 练习模式下的子选项 -->
      <div v-if="examMode === 'practice'" class="practice-options">
        <h3>练习模式选项</h3>
        <div class="practice-mode-options">
          <div 
            :class="['mode-option', { active: practiceMode === 'chapter' }]"
            @click="practiceMode = 'chapter'"
          >
            <h4>章节练习</h4>
            <p>按章节练习题目</p>
          </div>
          
          <div 
            :class="['mode-option', { active: practiceMode === 'random' }]"
            @click="practiceMode = 'random'"
          >
            <h4>随机练习</h4>
            <p>从题库中随机抽取题目练习</p>
            <p class="question-count">题目数量：单选38题，多选38题，判断38题</p>
          </div>
          
          <div 
            :class="['mode-option', { active: practiceMode === 'wrong' }]"
            @click="practiceMode = 'wrong'"
          >
            <h4>错题库练习</h4>
            <p>从历史错题中随机抽取题目练习</p>
            <p class="question-count">题目数量：单选40题，多选40题，判断40题</p>
          </div>
        </div>
        
        <!-- 章节选择 -->
        <div v-if="practiceMode === 'chapter'" class="chapter-selection">
          <h4>选择章节</h4>
          <div class="chapter-options">
            <div
              v-for="chapter in 8"
              :key="chapter"
              :class="['chapter-option', { active: selectedChapter === chapter }]"
              @click="selectedChapter = chapter"
            >
              第{{ chapter }}章
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="actions">
      <button @click="generateExam" class="generate-btn">开始{{ examMode === 'exam' ? '考试' : (practiceMode === 'chapter' ? '章节练习' : practiceMode === 'wrong' ? '错题库练习' : '随机练习') }}</button>
      <button @click="viewExamRecords" class="records-btn">查看考试记录</button>
    </div>
  </div>
</template>

<style scoped>
.exam-entry {
  width: 100%;
  max-width: 600px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  text-align: center;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.description {
  color: #666;
  font-size: 16px;
  margin-bottom: 30px;
}

.mode-selection {
  margin-bottom: 30px;
}

.mode-selection h3 {
  margin-bottom: 20px;
  color: #333;
}

.mode-options,
.practice-mode-options {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.mode-option {
  flex: 1;
  padding: 20px;
  border: 2px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.mode-option:hover {
  border-color: #409eff;
}

.mode-option.active {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.2);
}

.mode-option h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.mode-option p {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
}

.mode-option .question-count {
  font-weight: bold;
  color: #409eff;
}

.practice-options {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.chapter-selection {
  margin-top: 20px;
}

.chapter-selection h4 {
  margin-bottom: 15px;
  color: #333;
}

.chapter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.chapter-option {
  padding: 10px 15px;
  border: 2px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.chapter-option:hover {
  border-color: #409eff;
}

.chapter-option.active {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.2);
}

.generate-btn {
  width: 100%;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 10px;
}

.generate-btn:hover {
  background-color: #0056b3;
}

.records-btn {
  width: 100%;
  padding: 12px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.records-btn:hover {
  background-color: #218838;
}
</style>